//
//  TableViewController.m
//  BaseTdkc
//
//  Created by DavidHuang on 16/7/1.
//  Copyright © 2016年 黄栋炜. All rights reserved.
//

#import "TableViewController.h"
#import "MJRefresh.h"
#import "MJExtension.h"
#import "BaseRequest.h"
#import "SearchPromptPageView.h"
#import "NetworkLoadInView.h"
#import "Utility.h"
typedef NS_ENUM(NSInteger, RequestResultState) {
    RequestResultStateNormal,
    RequestResultStateNoData,
    RequestResultStateNoNet
};
@interface RequestParamModel : NSObject
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger rows;
@end
@implementation RequestParamModel
@end
@interface TableViewController ()
@property (nonatomic, strong) RequestParamModel *paraModel;
@property(nonatomic,strong)SearchPromptPageView * noInforView;
@property(nonatomic,strong)SearchPromptPageView * networkAnomalyView;
@property(nonatomic,strong)NetworkLoadInView * loadInView;
- (void)refreshInfoRequest;
@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.requestType = RequestTypePost;
    self.dataArray = [NSMutableArray arrayWithCapacity:10];
    self.requestKeyString = @"";
    self.paraModel.page = 1;
    self.paraModel.rows = 10;
    self.parameter = [NSDictionary dictionary];
    
}

- (void)refreshInfoRequest {
    [self.noInforView removeFromSuperview];
    [self.networkAnomalyView removeFromSuperview];
    [self.loadInView removeFromSuperview];
    [self.tableView addSubview:self.loadInView];
    
    if ([self isCanRequest]) {
        _paraModel.page = 1;
        NSMutableDictionary *paraDic = [_paraModel mj_keyValues];
        [paraDic addEntriesFromDictionary:self.parameter];
        [[BaseRequest shareInstance] sendRequestType:self.requestType Url:self.requestKeyString parameter:paraDic success:^(NSDictionary *source) {
            [_tableView.mj_header endRefreshing];
            if ([source[@"data"][@"rows"] count] == 0) {
                [self updateRequestResultState:RequestResultStateNoData];
                if (self.dataArray.count == 0){
                    [self.networkAnomalyView removeFromSuperview];
                    [self.loadInView removeFromSuperview];
                    [self.tableView addSubview:self.noInforView];
                }
            }
            if (source[@"data"][@"rows"] && [source[@"data"][@"rows"] count] >= 1) {
                
                [self.noInforView removeFromSuperview];
                [self.networkAnomalyView removeFromSuperview];
                [self.loadInView removeFromSuperview];
                
                [_dataArray removeAllObjects];
                [_dataArray addObjectsFromArray:source[@"data"][@"rows"]];
            }
            if (_dataArray.count == 0) {
                [self updateRequestResultState:RequestResultStateNoData];
            } else {
                [_tableView reloadData];
            }
        } fail:^(NSError *error) {
            [self.noInforView removeFromSuperview];
            [self.loadInView removeFromSuperview];
            [self.tableView  addSubview: self.networkAnomalyView];
            [_tableView.mj_header endRefreshing];
        }];
    }
}

- (void)loadMoreInfoRequest {
    if ([self isCanRequest]) {
        if (_dataArray.count%_paraModel.rows == 0 && _dataArray.count > 0) {
            _paraModel.page = _dataArray.count/_paraModel.rows + 1;
        } else {
            [_tableView.mj_footer endRefreshing];
            [MBProgressHUD showSuccess:@"没有更多内容"];
            return;
        }
        NSMutableDictionary *paraDic = [_paraModel mj_keyValues];
        [paraDic addEntriesFromDictionary:self.parameter];
        [[BaseRequest shareInstance] sendRequestType:self.requestType Url:self.requestKeyString parameter:paraDic success:^(NSDictionary *source) {
            [_tableView.mj_footer endRefreshing];
            if (source[@"data"][@"rows"] && [source[@"data"][@"rows"] count] >= 1) {
                _paraModel.page =_paraModel.page + 1;
                [_dataArray addObjectsFromArray:source[@"data"][@"rows"]];
            }
            if (_dataArray.count == 0) {
                [self updateRequestResultState:RequestResultStateNoData];
            } else {
                [_tableView reloadData];
            }
        } fail:^(NSError *error) {
            [_tableView.mj_footer endRefreshing];
        }];
    }
}

- (BOOL)isCanRequest {
    if (![Utility getNetStatus]) {
        [_tableView.mj_header endRefreshing];
        [self updateRequestResultState:RequestResultStateNoNet];
        return NO;
    } else {
        [self updateRequestResultState:RequestResultStateNormal];
        return YES;
    }
}

- (void)addRefreshHeader {
    MJRefreshNormalHeader *refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshInfoRequest)];
    refreshHeader.lastUpdatedTimeLabel.hidden = NO;
    refreshHeader.stateLabel.hidden = NO;
    self.tableView.mj_header = refreshHeader;
}

- (void)addLoadMoreFooter {
    MJRefreshAutoNormalFooter *loadMoreFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreInfoRequest)];
    loadMoreFooter.automaticallyHidden = YES;
    loadMoreFooter.refreshingTitleHidden = NO;
    self.tableView.mj_footer = loadMoreFooter;
}

- (void)updateRequestResultState:(RequestResultState)state {
    switch (state) {
        case RequestResultStateNoNet:
            [_dataArray removeAllObjects];
            [_tableView reloadData];
            //            _tableView.backgroundView = self.noNetView;
            _tableView.scrollEnabled = NO;
            break;
        case RequestResultStateNoData:
            [_dataArray removeAllObjects];
            [_tableView reloadData];
            //            _tableView.backgroundView = self.noDataView;
            _tableView.scrollEnabled = NO;
            break;
        case RequestResultStateNormal:
            _tableView.backgroundView = nil;
            _tableView.scrollEnabled = YES;
            break;
        default:
            break;
    }
}

- (void)beginRequestInfo {
    [self refreshInfoRequest];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = [UIColor colorOfBackgroudColor];
        _tableView.tableFooterView = [UIView new];
        [self.view addSubview:self.tableView];
    }
    return _tableView;
}

- (RequestParamModel *)paraModel {
    if(_paraModel == nil) {
        _paraModel = [[RequestParamModel alloc] init];
    }
    return _paraModel;
}
-(SearchPromptPageView *)noInforView{
    if (_noInforView == nil) {
        _noInforView = [[SearchPromptPageView alloc]init];
        _noInforView.titleLbStr = @"暂无结果";
        _noInforView.promptPageImgStr = @"no_info";
        _noInforView.isReloadBtn = NO;
        
        
    }
    return _noInforView;
}
-(SearchPromptPageView *)networkAnomalyView{
    if (_networkAnomalyView == nil) {
        _networkAnomalyView = [[SearchPromptPageView alloc]init];
        _networkAnomalyView.titleLbStr = @"网络异常";
        _networkAnomalyView.promptPageImgStr = @"wifi_errors";
        _networkAnomalyView.isReloadBtn = YES;
        [_networkAnomalyView.reloadBtn addTarget:self action:@selector(clickReloadBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _networkAnomalyView;
}
-(NetworkLoadInView *)loadInView{
    if (_loadInView == nil) {
        _loadInView = [[NetworkLoadInView alloc]init];
        _loadInView.titleLbStr = @"加载中";
        
        
    }
    return _loadInView;
}

-(void)clickReloadBtn:(UIButton *)sender{
    [self refreshInfoRequest];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
